// pages/mall/consult/index.js
const app = getApp();
const $api = require('../../../../request/api').API;
import { getElement } from '../../../../utils/util';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    menuBtnTop: app.globalData.menuBtnTop, //设备顶部到胶囊的距离,
    menuBtnHeight: app.globalData.menuBtnHeight, //右上角胶囊的高度,
    classifyIds: '',
    beeperId: '',
    pageNum: 1,
    pageSize: 10,
    totalPage: 0,
    libraryName: '',
    provinceName: '',
    cityName: '',
    areaName: '',
    address: '',
    leftList: [],
    rightList: [],
    tagList: [],
    tagIds: [],
    empty: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      beeperId: app.globalData['btnList.beeperId'],
      classifyIds: app.globalData['btnList.btnServerClassifyIds']
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.init();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const { address, provinceName, cityName, areaName, latitude, longitude } = app.globalData;
    if (address) {
      this.setData({
        provinceName,
        cityName,
        areaName,
        address,
        pageNum: 1
      });
      this.getData();
      delete app.globalData.address;
      delete app.globalData.latitude;
      delete app.globalData.longitude;
      delete app.globalData.provinceName;
      delete app.globalData.cityName;
      delete app.globalData.areaName;
    }
  },
  async init() {
    await this.getTagList();
    const res = await getElement('.top-fixed');
    this.setData({
      topFixedHeight: res[0].height
    });
    await this.getData();
  },
  back() {
    wx.navigateBack({
      delta: 1
    });
  },
  async getData() {
    const { beeperId, pageNum, pageSize, libraryName, tagIds, cityName, provinceName, areaName, classifyIds } =
      this.data;
    const params = {
      beeperId,
      pageNo: pageNum,
      pageSize,
      libraryName,
      cityName,
      provinceName,
      areaName,
      tagIds: tagIds.toString(),
      secondClassifyIds: classifyIds
    };
    // this.break = true
    let res = await $api.getLibraryList(params);
    if (pageNum == 1) {
      wx.pageScrollTo({
        scrollTop: 0
      });
      this.setData({
        leftList: [],
        rightList: []
      });
    }

    // delete this.break
    const { list = [], totalPage } = res.data.data;
    this.setData({
      totalPage,
      empty: list.length ? false : true
    });
    await this.waterFall(list);
  },
  async getTagList() {
    const res = await $api.getTagList({ secondClassifyIds: this.data.classifyIds });
    this.setData({
      tagList: res.data.data || []
    });
  },
  // 搜索
  async handleSearch() {
    this.setData({
      pageNum: 1,
      leftList: [],
      rightList: []
    });
    await this.getData();
  },
  // 输入
  handleInput(e) {
    this.setData({
      libraryName: e.detail
    });
  },
  // 点击标签
  async handleClickTag(e) {
    const { tagIds, tagList } = this.data;
    const { id } = e.currentTarget.dataset;
    const index = tagIds.findIndex(item => item == id);
    if (index != -1) {
      tagIds.splice(index, 1);
    } else {
      tagIds.push(tagList.find(item => item.id == id).id);
    }
    this.setData({
      tagIds,
      pageNum: 1,
      leftList: [],
      rightList: []
    });
    wx.pageScrollTo({
      scrollTop: 0
    });
    await this.getData();
  },
  // 点赞
  async handleClickLike() {},
  // // 图片加载
  // handleImageLoad(e){
  //   console.log("图片加载完毕")
  //   this.imgLoading = true
  //   if(this.imgLoadFunc){
  //     this.imgLoadFunc()
  //     this.imgLoadFunc = null
  //   }
  // },
  async waterFall(list) {
    // 这里需要做一个全局的标识，二次请求的时候如果还上一次没有结束那么就停止上一次的渲染
    if (this.data.pageNum == 1) {
      this.globalFlag = true;
    }
    // 这个scroll是保证渲染完成后才可以进行滚动继续请求数据
    this.scroll = false;
    for (let i in list) {
      if (this.globalFlag && this.data.pageNum != 1) break;
      await this.setItem(list[i]);
    }
    this.scroll = true;
    this.globalFlag = false;
  },
  setItem(item) {
    let leftList = this.data.leftList;
    let rightList = this.data.rightList;
    return new Promise(resolve => {
      Promise.all([getElement('#left-list'), getElement('#right-list')]).then(res => {
        let leftElement = res[0][0];
        let rightElement = res[1][0];

        if (this.globalData) return;
        if (leftElement.height > rightElement.height) {
          rightList.push(item);
        } else {
          leftList.push(item);
        }
        this.setData(
          {
            leftList,
            rightList
          },
          function () {
            // if(this.imgLoading){
            //   this.imgLoading = false
            //   resolve()
            // }else{
            //   this.imgLoadFunc = ()=>{
            //     console.log("执行")
            //     resolve()
            //     this.imgLoading = false
            //   }
            // }
            setTimeout(() => {
              resolve();
            }, 50);
          }
        );
      });
    });
  },
  // 选择位置
  async toSelectLocation() {
    wx.navigateTo({
      url:
        '/subcontract/home/pages/selectLocation/index?address=' +
        this.data.address +
        '&province=' +
        this.data.provinceName
    });
  },
  toConsultDetail(e) {
    wx.navigateTo({
      url: '/subcontract/home/pages/consultDetail/index?id=' + e.currentTarget.dataset.id
    });
  },
  // 去商品详情页面
  toGoodsDetail(e) {
    let goodsId = e.currentTarget.dataset.goodsid;
    let beeperBtnId = e.currentTarget.dataset.beeperBtnId;
    wx.navigateTo({
      url: '/subcontract/home/pages/goodsDetail/index?goodsId=' + goodsId + '&beeperBtnId=' + beeperBtnId
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},
  /**
   *  页面滚动
   */
  onPageScroll(e) {
    // console.log(e)
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom(e) {
    let { pageNum, totalPage } = this.data;
    if (pageNum >= totalPage) return;
    this.setData({
      pageNum: ++pageNum
    });
    this.getData();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {}
});
